import json
import random
import re

from django import http
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from django_redis import get_redis_connection

from libs.aliyun.sms.sms import sms_app
from libs.captcha.captcha import captcha
from utils import contents
from utils.email import Email
from utils.response_code import RETCODE
from utils.views import LoginRequiredJsonMixin


class ImageCodeView(View):
    def get(self, request, uuid):
        _, text, image = captcha.generate_captcha()
        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_%s' % uuid, contents.IMAGE_CODE_REDIS_EXPIRES, text)

        return http.HttpResponse(image, content_type='image/jpeg')


class SMSCodeView(View):
    def get(self, request, mobile):

        redis_conn = get_redis_connection('code')
        send_sms_flag = redis_conn.get('sms_%s' % mobile)
        if send_sms_flag:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '发送频繁'})

        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('uuid')

        if not all([image_code_client, uuid]):
            return http.JsonResponse({'code': RETCODE.NECESSARYPARAMERR, 'errmsg': '缺少参数'})

        image_code_server = redis_conn.get('img_%s' % uuid)
        if image_code_server is None:
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '验证码错误'})

        try:
            redis_conn.delete('img_%s' % uuid)
        except Exception as e:
            print(e)

        if image_code_server.decode().lower() != image_code_client.lower():
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '输入短信验证码错误'})

        sms_code = '%06d' % random.randint(0, 999999)

        redis_conn.setex('sms_%s' % mobile, contents.IMAGE_CODE_REDIS_EXPIRES, sms_code)

        # sms_app.send_task('sms.send_sms_t', args=[mobile, sms_code])  # 没有阿里云暂时注释了
        ret = sms_app.send_task('sms.send_sms_f')
        print(ret)
        print('<<<<<短信验证码>>>>>', sms_code)

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '发送短信成功'})


class EmailView(LoginRequiredJsonMixin, View):
    def put(self, request):
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')

        if not email:
            return http.HttpResponseBadRequest('缺少email参数')

        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseBadRequest('参数email有误')

        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '添加邮箱失败'})

        ret = Email.send_email(request, email)
        print('>>>>>>>发送邮件>>>>>>>', ret)

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加邮箱成功'})


class VerifyEmailView(View):
    def get(self, request):
        token = request.GET.get('token')

        if not token:
            return http.HttpResponseBadRequest('缺少token')

        user = Email.verify_email(token)
        if not user:
            return http.HttpResponseBadRequest('无效的token')

        try:
            user.email_active = True
            user.save()
        except Exception as e:
            return http.HttpResponseBadRequest('邮件激活失败')

        return redirect(reverse('users:user_center'))
